package com.california.payopenapi.service;

import com.california.pay.model.MchOrderPayNotifyMchReq;
import com.california.payopenapi.dao.PmchInfoDao;
import com.california.payopenapi.utils.HttpUtil;
import com.california.payopenapi.utils.JsonUtil;
import com.california.payopenapi.utils.MD5Sign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @author: KeyboardMan
 * @Date: Create in 2018-12-19:21:25
 */
@Slf4j
@Service
public class HttpService {

    @Autowired
    PmchInfoDao infoDao;

    public String execute(long money) {
        return HttpUtil.post(money);
    }


    public boolean notifyMch(MchOrderPayNotifyMchReq notifyMchReq) {

        String mchId = notifyMchReq.getInnerMchNo(); //notifyMchReq.getMchId();
        log.info("执行商户异步通知HTTP SERVICE  商户ID  {}  订单编号  {}",mchId,notifyMchReq.getInnerOrderNo());
        String resSecret = infoDao.getResSecret(mchId);
        // 进行返回参数签名
        Map<String,Object> params = new HashMap<>();
        params.put("outOrderNo",notifyMchReq.getOutOrderNo());
        params.put("innerOrderNo",notifyMchReq.getInnerOrderNo());
        params.put("totalAmount",notifyMchReq.getTotalAmount());
        params.put("txnAmount",notifyMchReq.getTxnAmount());
        params.put("remark",notifyMchReq.getRemark());
        // LocalDateTime 格式化成字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = notifyMchReq.getSystemTime().format(formatter);
        params.put("systemTime",formattedDateTime);
        String sign = MD5Sign.sign(params,resSecret);
        params.put("sign",sign);

        String reqJson = JsonUtil.obj2String(params);
        log.info("请求参数 {}",reqJson);

        log.info("参数构建完毕");
        String result = HttpUtil.postJson(notifyMchReq.getNotifyUrl(),reqJson );
        if (result.equals(StringUtils.EMPTY)) {
            return false;
        } else {
            if (result.equals(notifyMchReq.getInnerOrderNo())) {
                log.info("异步通知成功, 返回订单号校验通过");
                return true;
            }
            return false;
        }
    }
}
